package cs.java.event;

import static cs.java.lang.Lang.is;

import cs.java.event.Event.EventRegistration;
import cs.java.lang.Run;

public abstract class Task implements Run, Listener {

	protected Object argument;
	protected EventRegistration registration;
	protected Event<?> event;

	public Task(Event<?>... events) {
		for (Event<?> event : events)
			event.add(this);
	}

	public Task(EventConsumer parent, Event<?>... events) {
		for (Event<?> event : events)
			add(parent, event, event.toString());
	}

	public Task(EventConsumer parent, Event<?> event, String id) {
		add(parent, event, id);
	}

	private void add(EventConsumer parent, Event<?> event, String id) {
		EventRegistration registration = parent.removeRegistration(id);
		if (is(registration)) registration.cancel();
		parent.addRegistration(id, event.add(this));
	}

	public <T> void onEvent(Event<T> event, EventRegistration registration, T argument) {
		this.event = event;
		this.registration = registration;
		this.argument = argument;
		run();
	}

}